﻿using System.Collections.Generic;

namespace Gameplay.PVE
{
    public class PveBattleBulletsMgr
    {
        private static PveBattleBulletsMgr instance;

        public static PveBattleBulletsMgr Ins
        {
            get
            {
                if (instance == null)
                    instance = new PveBattleBulletsMgr();

                return instance;
            }
        }

        private Dictionary<int, int> bulletCache = new Dictionary<int, int>(32);

        private Dictionary<int, bool> skillCastingCache = new Dictionary<int, bool>(32);

        private PveBattleBulletsMgr()
        {
            PveManager.Instance.onBattleFinish += () =>
            {
                this.bulletCache = new Dictionary<int, int>(32);
                this.skillCastingCache = new Dictionary<int, bool>(32);
            };
        }

        public int GetBulletID(int unitID, int teamID, int skillSlot, int shootWave)
        {
            var ret = GenID(unitID, teamID, skillSlot, shootWave);
            if (this.bulletCache.ContainsKey(ret))
                this.bulletCache[ret] += 1;
            else
                this.bulletCache.Add(ret, 1);
            
            return ret;
        }
        
        public void OnBulletDispose(int bulletID)
        {
            if (!this.bulletCache.ContainsKey(bulletID))
                return;

            this.bulletCache[bulletID] -= 1;
            CheckBulletDamageEnd(bulletID);
        }

        public void SetSkillCastingState(int unitID, int teamID, int skillSlot, int shootWave, bool state)
        {
            var id = GenID(unitID, teamID, skillSlot, shootWave);
            this.skillCastingCache[id] = state;
            CheckBulletDamageEnd(id);
        }

        public int GetTeamByBulletID(int bulletID)
        {
            return (bulletID / 1000) % 10;
        }

        private int GenID(int unitID, int teamID, int skillSlot, int shootWave)
        {
            return shootWave + teamID * 1000 + skillSlot * 10000 + unitID * 1000000;
        }
        
        private void CheckBulletDamageEnd(int id)
        {
            if (!this.skillCastingCache.ContainsKey(id))
                return;

            if (!this.bulletCache.ContainsKey(id))
                return;

            if (this.bulletCache[id] == 0 && !this.skillCastingCache[id])
                PveFlyTextManager.Instance.EndNormalAttackText(id);
        }
    }
}